// pages/location/userUpdate/userUpdate.ts
import { setUserInfo } from '../../../http/api/userServiceApi'
const { Config } = require('../../../lib/config')
const BASE_UPLOAD_URL = Config.BASE_UPLOAD_URL
const BASE_URL = Config.BASE_URL
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        linkman: '',
        linemanTip: '',
        phone: '',
        phoneTip: '',
        fileList: [],
        avatarUrl: '',
        showLogoutConfirm: false
    } as any,

    handleAdd(e: any) {
        const { fileList }: any = this.data
        const { files } = e.detail

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        this.setData({
            fileList: [...fileList, ...files] // 此时设置了 fileList 之后才会展示选择的图片
        })
        console.log(this.data.fileList)
        this.uploadFile(this.data.fileList[0])
    },
    uploadFile(file: any) {
        const { fileList } = this.data

        this.setData({
            fileList: [...fileList, { ...file, status: 'loading' }]
        })
        const { length } = fileList
        console.log(file.url, '-----file')
        const token = wx.getStorageSync('token')
        const openid = wx.getStorageSync('openid')
        const task = wx.uploadFile({
            url: BASE_UPLOAD_URL + '/api/UploadFile', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'file',
            header: {
                token,
                openid
            },
            formData: { Files: file.url },
            success: (res: any) => {
                console.log(res, '---success')
                this.setData({
                    [`fileList[${length}].status`]: 'done'
                })
                const { data } = JSON.parse(res.data)
                const url = `${BASE_UPLOAD_URL}${data[0]}`
                console.log(url, '---success')
                this.setData({
                    avatarUrl: url
                })
            },
            fail: function (error) {
                console.log(error)
            }
        })
        task.onProgressUpdate(res => {
            this.setData({
                [`fileList[${length}].percent`]: res.progress
            })
        })
    },
    handleRemove(e: any) {
        const { index } = e.detail
        const { fileList } = this.data

        fileList.splice(index, 1)
        this.setData({
            fileList
        })
    },

    async update() {
        const { linkman, phone, avatarUrl } = this.data
        console.log(linkman, phone, avatarUrl)
        if (!this.valid()) {
            return
        }
        const userInfo = {
            user_icon: avatarUrl, //用户的头像
            user_sname: linkman, //用户的昵称
            user_tel: phone //用户的电话
        }
        console.log(userInfo)
        const res = await setUserInfo(userInfo)
        wx.navigateBack()
        console.log(res, '---res')
    },

    valid() {
        const { linkman, phone, avatarUrl } = this.data

        if (linkman === '') {
            this.setData({
                linemanTip: '联系人不能为空'
            })
            return false
        } else {
            this.setData({
                linemanTip: ''
            })
        }
        if (phone === '') {
            this.setData({
                phoneTip: '手机号不能为空'
            })
            return false
        } else if (!this.checkTelephone(phone)) {
            this.setData({
                phoneTip: '请输入正确的手机号'
            })
            return false
        } else {
            this.setData({
                phoneTip: ''
            })
        }

        if (avatarUrl == '') {
            wx.showToast({
                title: '未上传头像',
                icon: 'error',
                duration: 1000
            })
            return false
        }

        return true
    },

    logout() {
        wx.removeStorageSync('token')
        wx.removeStorageSync('openid')
        wx.navigateBack()
    },

    closeDialog() {
        this.setData({
            showLogoutConfirm: false
        })
    },

    showDialog() {
        this.setData({
            showLogoutConfirm: true
        })
    },

    checkTelephone(telephone: string) {
        const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/
        return reg.test(telephone)
    },

    checkIdCard(idCard: string) {
        const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        return reg.test(idCard)
    },

    handlerPhoneInput(InputValue: any) {
        console.log(InputValue)
        this.setData({
            phone: InputValue.detail.value
        })
    },

    handlerLinkManInput(InputValue: any) {
        console.log(InputValue)
        this.setData({
            linkman: InputValue.detail.value
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        const user = app.globalData.userInfo
        console.log(user)
        this.setData({
            linkman: user.user_sname,
            phone: user.user_tel,
            fileList: [
                {
                    url: user.user_icon,
                    name: 'uploaded1.png',
                    type: 'image'
                }
            ],
            avatarUrl: user.user_icon
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {}
})
